<template>
  <div>
    <h3>分类参数</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <!-- 警告区域 :closable="false"(是否展示“X”号) show-icon(显示图标) -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
    </el-card>
    <!-- 选择商品分类区域 -->
    <el-card>
      <el-row class="cat_opt">
        <el-col :span="5">
          <span>选择商品分类：</span>
        </el-col>
        <el-col :span="19">
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="动态参数" name="many">
          <el-table :data="manyData" stripe border style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- tags -->
              <template slot-scope="data">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in data.row.attr_vals"
                  closable
                  @close="handleClose(data.row, i)"
                  style="margin: 8px"
                >
                  {{ tag }}
                </el-tag>
                <el-button
                  size="small"
                  v-if="data.row.isShow === false"
                  class="button-new-tag"
                  @click="data.row.isShow = true"
                >
                  +newTag
                </el-button>
                <el-input
                  class="tagInput"
                  size="small"
                  v-else
                  v-el-focus
                  v-model="newTag"
                  @blur="data.row.isShow = false"
                  @keyup.enter.native="addNewTag(data.row)"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="data">
                <!-- 编辑参数面板 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(data)"
                ></el-button>
                <!-- 删除参数面板 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(data)"
                >
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            class="btnAdd"
            size="mini"
            type="primary"
            :disabled="isButtonDisabled"
            @click="addParams(manyData)"
            >添加参数</el-button
          >
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-table :data="onlyData" stripe border style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- tags -->
              <!-- tags -->
              <template slot-scope="data">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in data.row.attr_vals"
                  closable
                  @close="handleClose(data.row, i)"
                  style="margin: 8px"
                >
                  {{ tag }}
                </el-tag>
                <el-button
                  size="small"
                  v-if="data.row.isShow === false"
                  class="button-new-tag"
                  @click="data.row.isShow = true"
                >
                  +newTag
                </el-button>
                <el-input
                  class="tagInput"
                  size="small"
                  v-else
                  v-el-focus
                  v-model="newTag"
                  @keyup.enter.native="addNewTag(data.row)"
                  @blur="data.row.isShow = false"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="data">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(data.row)"
                ></el-button>
                <el-button type="danger" icon="el-icon-delete"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            size="mini"
            @click="addParams(onlyData)"
            class="btnAdd"
            type="primary"
            :disabled="isButtonDisabled"
            >添加属性</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 点击修改用户信息提示框 -->
    <el-dialog
      :title="'添加' + setTitle"
      :visible.sync="isAddParams"
      width="50%"
      @close="onClose"
    >
      <!-- 添加表单 -->
      <el-form
        :model="addModel"
        :rules="addFormRules"
        ref="addForm"
        label-width="100px"
      >
        <el-form-item :label="setTitle" prop="attr_name">
          <el-input v-model="addModel.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddParams = false">取 消</el-button>
        <el-button type="primary" @click="doAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击修改参数信息 -->
    <!-- 修改参数或属性对话框 -->
    <el-dialog
      :title="'修改' + setTitle"
      :visible.sync="isEditParams"
      width="50%"
      @close="onClose"
    >
      <!-- 添加表单 -->
      <el-form
        :model="editModel"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="setTitle" prop="attr_name">
          <el-input v-model="editModel.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditParams = false">取 消</el-button>
        <el-button type="primary" @click="doEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Service } from '../../service'
export default {
  data() {
    return {
      //分类列表
      cateList: [],
      //用户在级联下拉菜单中选中的分类id
      selectedCateKeys: [],
      //配置级联菜单中数据如何展示
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: false,
      },
      //数据总条数
      total: 0,
      //tab分页
      activeName: 'many',
      // manydata
      manyData: [],
      // onlydata
      onlyData: [],
      // 开启添加参数面板
      isAddParams: false,
      // 开启编辑参数对话框
      isEditParams: false,
      // 添加属性绑定数据
      addModel: {
        attr_name: '',
        attr_sel: '',
        attr_vals: '',
      },
      // 编辑属性绑定数据
      editModel: {
        attr_name: '',
        id: '',
        attr_sel: '',
        attr_vals: '',
      },
      // 添加的新标签
      newTag: '',
      //添加表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getAllCate()
  },
  methods: {
    // 级联父类选择框的选中事件
    async handleChange() {
      if (this.selectedCateKeys.length < 3) {
        this.selectedCateKeys = []
        return this.$message.error('必选选择三级分类喔')
      }
      const id = this.getCateId
      const res = await Service.getParams(id, this.activeName)
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        // 将attr_vals拆分为数组
        console.log('这是啦啦啦啦', res.data)
        res.data.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 为attr_vals添加isshow属性
          item.isShow = false
        })
        if (this.activeName === 'many') {
          this.manyData = res.data.data
        } else {
          this.onlyData = res.data.data
        }
      }
    },
    // 获取所有的分类菜单
    async getAllCate() {
      const res = await Service.getCategories({})
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        this.cateList = res.data.data
        this.total = res.data.data.length
      }
    },
    // 编辑参数
    editParams(data) {
      this.isEditParams = true
      this.editModel.attr_name = data.row.attr_name
      this.editModel.id = data.row.attr_id
      this.editModel.attr_sel = this.activeName
    },
    // 确认修改
    async doEdit() {
      this.isEditParams = false
      const data = {
        attr_name: this.editModel.attr_name,
        attr_sel: this.editModel.attr_sel,
      }
      const res = await Service.editParams(
        this.getCateId,
        this.editModel.id,
        data
      )
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        this.handleChange()
      }
    },
    // 开启添加参数面板
    addParams(data) {
      console.log(data)
      this.isAddParams = true
      this.addModel.attr_sel = this.activeName
      this.addModel.attr_vals = ''
    },
    // 确认添加属性
    async doAdd() {
      console.log(this.addModel)
      this.isAddParams = false
      const res = await Service.addParams(this.getCateId, this.addModel)
      if (res.data.meta.status !== 201) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        // if (this.activeName === 'many') {
        //   this.manyData.push(res.data.data)
        // } else {
        //   this.onlyData.push(res.data.data)
        // }
        this.handleChange()
      }
    },
    // 开启删除参数面板
    async deleteParams(data) {
      try {
        await this.$msgBox.confirm('删除数据后不可恢复,您还要继续么', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        const res = await Service.deleteParams(this.getCateId, data.row.attr_id)
        this.$message.success(res.data.meta.msg)
        this.handleChange()
      } catch (error) {
        console.log(error)
      }
    },
    // 清除表单数据
    onClose() {
      this.$refs.addForm && this.$refs.addForm.resetFields()
    },
    // 添加标签
    addNewTag(data) {
      data.isShow = false
      if (this.newTag) {
        data.attr_vals.push(this.newTag)
        const obj = {
          attr_name: data.attr_name,
          attr_sel: data.attr_sel,
          attr_vals: data.attr_vals.join(' '),
        }
        this.saveTag(data, obj)
      }
    },
    // 删除标签
    async handleClose(data, i) {
      try {
        await this.$msgBox.confirm('删除数据后不可恢复,您还要继续么', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        this.$set(data.attr_vals.splice(i, 1))
        const obj = {
          attr_name: data.attr_name,
          attr_sel: data.attr_sel,
          attr_vals: data.attr_vals.join(' '),
        }
        this.saveTag(data, obj)
      } catch (error) {
        console.log(error)
      }
    },
    // 更新标签
    async saveTag(data, obj) {
      const res = await Service.addTag(data.cat_id, data.attr_id, obj)
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        this.newTag = ''
      }
    },
  },
  computed: {
    //   控制动态参数和静态属性button的显示
    isButtonDisabled() {
      if (this.selectedCateKeys.length < 3) {
        return true
      } else {
        return false
      }
    },
    // 当前选中的三级分类的id
    getCateId() {
      return this.selectedCateKeys[2]
    },
    // 设置弹出添加框当前title
    setTitle() {
      if (this.activeName === 'many') {
        return '参数'
      } else {
        return '属性'
      }
    },
  },
}
</script>

<style scoped>
.btnAdd {
  margin-top: 20px;
}
.tagInput {
  width: 100px;
}
</style>